package com.github.shiqiyue.myadmin.controller.system.role;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.shiqiyue.myadmin.config.security.anontation.Authority;
import com.github.shiqiyue.myadmin.config.security.anontation.AuthorityConfig;
import com.github.shiqiyue.myadmin.config.security.common.AuthorityCommon;
import com.github.shiqiyue.myadmin.config.syslog.anontation.SysLog;
import com.github.shiqiyue.myadmin.controller.base.AdminBaseController;
import com.github.shiqiyue.myadmin.entity.system.Button;
import com.github.shiqiyue.myadmin.entity.system.CommonlyAuthority;
import com.github.shiqiyue.myadmin.entity.system.Menu;
import com.github.shiqiyue.myadmin.entity.system.Role;
import com.github.shiqiyue.myadmin.service.system.button.ButtonService;
import com.github.shiqiyue.myadmin.service.system.menu.MenuService;
import com.github.shiqiyue.myadmin.service.system.role.RoleService;
import com.github.shiqiyue.myadmin.service.system.rolebutton.RoleButtonService;
import com.github.shiqiyue.myadmin.service.system.rolecommonlyauthority.RoleCommonlyAuthorityService;
import com.github.shiqiyue.myadmin.service.system.rolemenu.RoleMenuService;
import com.github.shiqiyue.myadmin.service.system.user.UserService;
import com.github.shiqiyue.myadmin.util.json.JsonUtils;
import com.github.shiqiyue.myadmin.vo.rep.base.RepBase;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/***
 * 角色控制器
 *
 * @author wwy
 *
 */
@Controller
@AuthorityConfig(prefix = "/admin/role/list")
@RequestMapping(value = "admin/role")
public class RoleController extends AdminBaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @Autowired
    private ButtonService buttonService;

    @Autowired
    private RoleButtonService roleButtonService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private RoleCommonlyAuthorityService roleCommonlyAuthorityService;

    /***
     * 角色列表-页面
     * @return
     */
    @Authority(name = AuthorityCommon.LIST)
    @GetMapping("list")
    public String listPage() {
        return "pages/role/role-list";
    }

    /***
     * 列表数据
     * @param order
     * @param sort
     * @return
     */
    @Authority(name = AuthorityCommon.LIST)
    @PostMapping("list")
    @ResponseBody
    public RepBase listData(String order, String sort) {
        RepBase rep = new RepBase();
        EntityWrapper<Role> entityWrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(sort)) {
            if ("desc".equals(order)) {
                entityWrapper.orderBy(sort, false);
            } else {
                entityWrapper.orderBy(sort, true);
            }
        }
        rep.setData(roleService.selectList(entityWrapper));
        return rep.setCommonSuccess();
    }

    /****
     * 新增页面
     * @param parentId
     * @param model
     * @return
     */
    @Authority(name = AuthorityCommon.ADD)
    @GetMapping(value = "/add")
    public String toAdd(String parentId, Model model) {
        Role entity = new Role();
        entity.setParentId(parentId);
        model.addAttribute("entity", entity);
        return "pages/role/role-edit";
    }

    /***
     * 新增操作
     * @param role
     * @return
     */
    @SysLog("角色-添加")
    @Authority(name = AuthorityCommon.ADD)
    @PostMapping("add")
    @ResponseBody
    public RepBase add(Role role) {

        if (StringUtils.isBlank(role.getParentId())) {
            role.setParentId(Role.ROLE_ROOT_ID);
        }
        role.setDelAble(Role.DelAble.YES);
        role.setIndexUrl("");
        roleService.insert(role);
        return RepBase.newIntance().setCommonSuccess();
    }

    /***
     * 修改页面
     * @param id
     * @return
     */
    @Authority(name = AuthorityCommon.EDIT)
    @GetMapping("edit")
    public String toEdit(String id, Model model) {
        Role entity = roleService.selectById(id);
        model.addAttribute("entity", entity);
        return "pages/role/role-edit";
    }

    /**
     * 保存修改
     *
     * @return
     * @
     */
    @SysLog("角色-修改")
    @Authority(name = AuthorityCommon.EDIT)
    @PostMapping("edit")
    @ResponseBody
    public RepBase edit(Role role) {

        roleService.edit(role);
        return RepBase.newIntance().setCommonSuccess();
    }

    /***
     * 删除操作
     * @param id
     * @return
     */
    @SysLog("角色-删除")
    @Authority(name = AuthorityCommon.DELETE)
    @PostMapping(value = "/del")
    @ResponseBody
    public RepBase deleteRole(@RequestParam String id) {
        RepBase rep = new RepBase<>();
        if (roleService.countByParentId(id) > 0) {
            // 下级有数据时，删除失败
            return rep.setCommonFail().setMes("含有下级角色，请先删除下级角色");
        }
        if (userService.countByRoleId(id) > 0) {
            return rep.setCommonFail().setMes("角色含有用户，请先删除用户");
        }
        // 执行删除
        roleService.deleteRoleById(id);
        return rep.setCommonSuccess();
    }

    @Authority(name = AuthorityCommon.EDIT)
    @GetMapping("menu/auth/edit")
    public String toEditMenuAuth(String id, Model model) {
        List<Menu> menuList = roleMenuService.selectAuthMenuByRoleId(id, false);
        String json = JsonUtils.beanToString(menuList);
        model.addAttribute("json", json);
        model.addAttribute("id", id);
        return "pages/role/menu-auth-edit";
    }

    @SysLog("角色-保存角色菜单权限")
    @Authority(name = AuthorityCommon.EDIT)
    @PostMapping(value = "/menu/auth/edit")
    @ResponseBody
    public RepBase editMenuAuth(@RequestParam String roleId, @RequestParam(value = "menuIds[]") List<String> menuIds) {
        roleMenuService.updateRoleMenus(roleId, menuIds);
        return RepBase.newIntance().setCommonSuccess();
    }

    @Authority(name = AuthorityCommon.EDIT)
    @GetMapping("button/auth/edit")
    public String toEditButtonAuth(String id, Model model) {
        List<Button> buttonList = buttonService.selectList(new EntityWrapper<>());
        model.addAttribute("buttonList", buttonList);
        model.addAttribute("id", id);
        return "pages/role/button-auth-edit";
    }

    @Authority(name = AuthorityCommon.EDIT)
    @PostMapping("button/auth/edit/data")
    @ResponseBody
    public RepBase getButtonAuthData(String roleId, String buttonId) {
        List<Menu> menuList = roleButtonService.selectAuthsByRoleIdAndButtonId(roleId, buttonId);

        return RepBase.newIntance().setCommonSuccess().setData(menuList);
    }

    @Authority(name = AuthorityCommon.EDIT)
    @GetMapping("commonly/auth/edit")
    public String toEditCommonlyAuth(String id, Model model) {
        List<CommonlyAuthority> authorities = roleCommonlyAuthorityService.selectAuthsByRoleId(id);
        model.addAttribute("authorities", authorities);
        model.addAttribute("id", id);
        return "pages/role/commonly-auth-edit";
    }

    @Authority(name = AuthorityCommon.EDIT)
    @PostMapping("commonly/auth/edit")
    @ResponseBody
    public RepBase editCommonlyAuth(String roleId, @RequestParam(name = "authorityIds", required = false) List<String> authorityIds) {
        roleCommonlyAuthorityService.updateRoleCommonlyAuthority(roleId, authorityIds);

        return RepBase.newIntance().setCommonSuccess();
    }


    @PostMapping("/button/auth/edit")
    @ResponseBody
    public RepBase buttonAuthEdit(String roleId, String buttonId,
                                  @RequestParam(value = "menuIds[]") List<String> menuIds) {
        RepBase rep = new RepBase();
        roleButtonService.updateRoleButtons(roleId, buttonId, menuIds);
        return rep.setCommonSuccess();
    }


}